from turbogears import controllers, expose, url
from model import *
from turbogears import identity, redirect
from cherrypy import request, response
import ubermarkup

# from uberwiki import json
# import logging
# log = logging.getLogger("uberwiki.controllers")

class Root(controllers.RootController):
    @expose(template="uberwiki.templates.list")
    # @identity.require(identity.in_group("admin"))
    def index(self):
        return dict(nodes = Node.select())

    @expose(template="uberwiki.templates.login")
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            raise redirect(forward_url)

        forward_url=None
        previous_url= request.path

        if identity.was_login_attempted():
            msg=_("The credentials you supplied were not correct or "
                   "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg=_("You must provide your credentials before accessing "
                   "this resource.")
        else:
            msg=_("Please log in.")
            forward_url= request.headers.get("Referer", "/")
            
        response.status=403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)

    @expose()
    def logout(self):
        identity.current.logout()
        raise redirect("/")


    @expose()
    def addFact(self, text, node_name):
        node = Node.byName(node_name.lower())
        fact = Fact(node=node, text=text)

        for name in ubermarkup.get_referances(text):
            fact.addNode(Node.byName(name))


        return redirect(url('/' + node_name))

    @expose()
    def addNode(self, name):
        name = name.lower()
        try:
            node = Node.byName(name)
        except SQLObjectNotFound:
            node = Node()
            Name(name=name, node=node)

        return redirect(url('/' + name))

    @expose('uberwiki.templates.viewpage')
    def default(self, node_name):
        node_name = node_name.lower()
        try:
            node = Node.byName(node_name)
        except SQLObjectNotFound :
            #TODO do something
            return

        return dict(name = node_name.title(),
                    node = node,
                    formulas = node.formulas)
    

